<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>可编辑表格页面</title>
  <!-- 引入Vue.js和Element UI的样式文件 -->
   <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
  <script src="../../element/vue.js"></script>
  <script src="../../element/index.js"></script>
  <script src="../../js/axios.min.js"></script>
  <style>
    .button-container {
      display: flex;

    }

    .button-container .el-button {
      margin-right: 100px;
    }
  </style>
  </style>
</head>

<body>
  <div id="app">
    <div class="button-container">
      <el-button type="primary" @click="addRow">添加关联人</el-button>

      <el-upload ref="upload" :limit="1" :auto-upload="false" action="http://localhost:8888/api/persons/upload"
        :on-change="handleChange" :before-upload="beforeUpload">
        <el-button type="primary" v-if="showChooseFileButton">选择文件</el-button>
        
      </el-upload>
      <el-button type="primary" @click="submit" v-if="showChooseFileButton">提交</el-button>

    </div>
    <el-table :data="persons" style="width: 100%">
      <el-table-column prop="personId" label="关联人ID">
        <template slot-scope="scope">
          <el-input v-model="scope.row.personId" size="small" :disabled="true"></el-input>
        </template>
      </el-table-column>

      <el-table-column prop="personName" label="姓名">
        <template slot-scope="scope">
          <el-input v-model="scope.row.personName" size="small" :disabled="!isEditingRow(scope.row)"></el-input>
        </template>
      </el-table-column>
      <el-table-column prop="personGender" label="性别">
        <template slot-scope="scope">
          <el-select v-model="scope.row.personGender" size="small" :disabled="!isEditingRow(scope.row)">
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column prop="personAge" label="年龄">
        <template slot-scope="scope">
          <el-input v-model="scope.row.personAge" size="small" :disabled="!isEditingRow(scope.row)"></el-input>
        </template>
      </el-table-column>
      <el-table-column prop="personRelationship" label="关系">
        <template slot-scope="scope">
          <el-input v-model="scope.row.personRelationship" size="small" :disabled="!isEditingRow(scope.row)"></el-input>
        </template>
      </el-table-column>
      <el-table-column prop="personPhone" label="电话">
        <template slot-scope="scope">
          <el-input v-model="scope.row.personPhone" size="small" :disabled="!isEditingRow(scope.row)"></el-input>
        </template>
      </el-table-column>
      <el-table-column prop="personIdCard" label="身份证号">
        <template slot-scope="scope">
          <el-input v-model="scope.row.personIdCard" size="small" :disabled="!isEditingRow(scope.row)"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button v-if="!scope.row.editing" type="primary" icon="el-icon-edit" size="small"
            @click="enterEdit(scope.row)"></el-button>
          <el-button v-else-if="scope.row.editing && !scope.row.new" type="success" icon="el-icon-check" size="small"
            @click="confirmEdit(scope.row)"></el-button>
          <el-button v-if="scope.row.editing" type="danger" icon="el-icon-close" size="small"
            @click="cancelEdit(scope.row)"></el-button>
          <!-- 1. 添加删除操作按钮 -->
          <el-button v-if="!scope.row.editing" type="danger" icon="el-icon-delete" size="small"
            @click="deleteRow(scope.row)"></el-button>

          <!-- 2. 添加上传文件按钮 -->
          <el-button v-else-if="scope.row.editing && !scope.row.new" type="info" icon="el-icon-upload" size="small"
            @click="uploadFile(scope.row)"></el-button>

          <!-- 3. 添加下载文件按钮 -->
          <el-button v-if="!scope.row.editing" type="text" icon="el-icon-download" size="small"
            @click="downloadFile(scope.row)"></el-button>

        </template>
      </el-table-column>
    </el-table>
  </div>

  <script>
    var userId = localStorage.getItem('userId');
    new Vue({
      el: "#app",

      data() {
        return {
          editingRow: null,
          persons: [],
          showChooseFileButton: false,//隐藏选择文件按钮
          fileName: '', // 添加一个属性来存储文件名
          file: null,
          fileId: null, // 添加一个变量用以存储需要传递的ID
          scope: {
            row: {
              personId: "" // 这里绑定到scope.row.personId  
            }
          },
          isDisabled: true // 这个变量决定输入框是否被禁用  
        };

      },
        mounted() {
          var vm = this; // 保存Vue实例的引用
          this.getPersons(vm);
        },
        methods: {
          handleChange(file) {
            this.file = file.raw;
            this.fileName = file.name;
          },
          beforeUpload(file) {
            this.file = file;
            return false; // 阻止自动上传
          },
          async submit() {
      if (!this.file || !this.fileId) { // 确保文件和ID都存在
        this.$message.error('请先选择文件');
        return;
      }
      let formData = new FormData();
      formData.append('file', this.file);
      formData.append('personId', this.fileId); // 将ID添加到表单数据中
      
      try {
        const res = await axios.post('http://localhost:8888/api/persons/upload', formData, {
          headers: {
            'Content-Type': 'multipart/form-data',
          },
        });
        if (res.data.code === 0) {
          this.$message.success(res.data.message);
          this.file = null;
          this.fileName = '';
          this.showChooseFileButton = false;
          location.reload();
        } else {
          this.$message.error(res.data.message);
          location.reload();
        }
      } catch (err) {
        this.$message.error('文件上传失败');
      }
    },


        uploadFile(row) {
          this.fileId = row.personId; // 获取需要传递的ID
          this.showChooseFileButton = !this.showChooseFileButton; // 切换选择文件按钮状态
        },

        //样式函数
        enterEdit(row) {
        if (this.editingRow !== null) {
          // 如果已经有行处于编辑状态，则先取消之前的编辑
          this.cancelEdit(this.persons[this.editingRow]);
        }
            row.editing = true; // 退出编辑模式
            this.editingRow = this.persons.indexOf(row);
            row.originalData = { ...row }; // 保存原始数据
            this.isDisabled = false;
          },
         isEditingRow(row) {
          return this.editingRow === this.persons.indexOf(row);
        },
        confirmEdit(row) {
          // 点击确认按钮后，向服务器发送更新请求
          axios.put(`http://localhost:8888/api/persons/updatePersons`, row)
            .then(response => {
              console.log(response.data);
              this.editingRow = null;
              row.editing = false; // 退出编辑模式
              this.isDisabled = true
            })
            .catch(error => {
              this.editingRow = null;
              console.error(error);
            });

        },
        cancelEdit(row) {
          // 点击取消按钮后，恢复原始数据并退出编辑模式
          if (row.new) {
            this.editingRow = null;
            this.persons.splice(this.persons.indexOf(row), 1);
          } else {
            this.editingRow = null;
            Object.assign(row, row.originalData);
            row.editing = false;
          }
          this.isDisabled = true
        },
        //请求函数
        getPersons(vm) {
          // 发起HTTP GET请求，获取关联人列表   
          // 替换成实际的API调用
          axios.get('http://localhost:8888/api/persons/getPersons', {
            params: {
              userId: userId
            }
          })
            .then(function (response) {
              // 请求成功时的处理
              vm.persons = response.data.data;
            })
            .catch(function (error) {
              // 请求失败时的处理
              console.error(error);
            });
        },
        updatePerson(person) {
          // 发起HTTP PUT请求，更新关联人信息
          // 替换成实际的API调用
          axios.put(`http://localhost:8888/api/persons/updatePersons`, person)
            .then(response => {

              console.log(response.data);
            })
            .catch(error => {
              console.error(error);
            });
        },
        addRow() {
          // 向关联人列表中添加一行空数据
          this.persons.push({
            personName: '',
            personGender: '',
            personAge: '',
            personRelationship: '',
            personPhone: '',
            personIdCard: ''
          });

          // 使用 Axios 发送 POST 请求
          axios.post('http://localhost:8888/api/persons/addPerson', {
            userId: userId, // 替换为实际的用户ID
            personName: '',
            personGender: '',
            personAge: '',
            personRelationship: '',
            personPhone: '',
            personIdCard: ''
          })
            .then(response => {
              // 请求成功处理
              console.log('添加人员成功', response.data);
              alert("添加人员成功")
              // 可能还需要更新页面或者其他操作
              location.reload();

            })
            .catch(error => {
              // 请求失败处理
              console.error('添加人员失败', error);
              // 可能需要给用户一些提示或者进行其他处理
            });
        },
        deleteRow(person) {
          axios.post('http://localhost:8888/api/persons/deletePersons', { personId: person.personId })
            .then(response => {
              // 处理响应数据  
              alert("删除人员成功")
              // 可能还需要更新页面或者其他操作
              location.reload();
            })
            .catch(error => {
              // 处理错误  
              console.error(error);
            });
        },
        downloadFile(person) {
      axios({
        method: 'get',
        url: 'http://localhost:8888/api/persons/download',
        params: {
          personId: person.personId
        },
        responseType: 'arraybuffer'  // 设置响应类型为 arraybuffer，用于处理二进制数据
      }).then(response => {
        const blob = new Blob([response.data], { type: 'application/octet-stream' });
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', 'personFile.pdf');
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      }).catch(error => {
        this.$message.error("文件不存在")
        console.error('Error downloading file:', error);
        // 处理下载失败的情况
      });
    }

      }
    });

  </script>
</body>

</html>